
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using SqlSugar;
using System.Collections.Generic;
using System.Linq.Expressions;
using Util;

namespace API.Controllers
{
    public class CanteenPlanController : BaseController
    {
        Repository<tCanteenPlan> _CanteenPlan;
        Repository<tCanteenClient> _CanteenClient;
        Repository<tFile> _File;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public CanteenPlanController(Repository<tCanteenPlan> CanteenPlan, IMapper mapper, Repository<tCanteenClient> CanteenClient, Repository<tFile> File, ISqlSugarClient db)
        {
            _CanteenPlan = CanteenPlan;
            _mapper = mapper;
            _CanteenClient = CanteenClient;
            _File = File;
            _db = db;
        }

        /// <summary>
        /// 上传背景音乐
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> UpBGM([FromForm] IFormCollection formCollection)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                return await Task.Run(() =>
                {
                    FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
                    if (fileCollection == null || fileCollection.Count == 0)
                        return result.Error("未获取到文件");

                    var file = fileCollection[0];
                    int houzhuiIndex = file.FileName.LastIndexOf(".");//获取文件名中的点号的最后一个索引位置
                    string fileExt = file.FileName.Substring(0, houzhuiIndex);
                    return result.Success(UploadOperate.ReadSteam(file, "file/Canteen/BGM/", fileExt));
                });
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--UpBGM:"+ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 保存数据+上传方案文件
        /// </summary>
        /// <param name="formCollection">UploadInfo</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> SaveData([FromForm] IFormCollection formCollection)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                tCanteenPlan plan = new();
                if (formCollection.ContainsKey("UploadInfo"))
                {
                    SaveCanteenPlanInput input = JsonConvert.DeserializeObject<SaveCanteenPlanInput>(formCollection["UploadInfo"]);
                    plan = _mapper.Map<tCanteenPlan>(input);
                }
                FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;

                if (plan is null)
                {
                    return result.Error("主体信息不能为空");
                }

                if (string.IsNullOrEmpty(plan.FName))
                {
                    return result.Error("名称不能为空");
                }

                string planid = plan.Id;
                DateTime dt = DateTime.Now;
                plan.FChageDate = dt;
                InitEntity(plan);
                if (planid.Length > 0)
                {
                    //编辑方案
                    await _CanteenPlan.UpdateAsync(plan);
                }
                else
                {
                    plan.CreateTime = dt;
                    InitEntity(plan);
                    //新增方案
                    await _CanteenPlan.InsertAsync (plan);
                    planid = plan.Id;
                }

                if (fileCollection != null && fileCollection.Count > 0)
                {
                    var list = UploadOperate.UploadSteam(fileCollection, "file/Canteen/PlanFile/");

                    var max = await Task.Run(() => _db.Queryable<tFile>().Where(t => t.FPlanID.Equals(planid) && t.FShowType.Equals(plan.FShowType)).Max(t => t.FSort));
                    tFile f = new();
                    foreach (var item in list)
                    {
                        max++;
                        f = new();
                        f.FPlanID = planid;
                        f.FName = item;
                        f.FSort = max;
                        f.FShowType = plan.FShowType;
                        InitEntity (f);
                        await _File.InsertAsync(f);
                    }
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--SaveData:" + ex.ToString());
                return result.Exception();
            }
        }
        /// <summary>
        /// 分页获取方案
        /// </summary>
        /// <param name="inx"></param>
        /// <param name="row"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<GetPlanOutput>>> GetPlan(GetPlanInput dto)
        {
            ResultMsg<List<GetPlanOutput>> result = new ResultMsg<List<GetPlanOutput>>();
            try
            {
                Expressionable<tCanteenPlan, tCanteenClient> expressionable = Expressionable.Create<tCanteenPlan, tCanteenClient>();//实例化Expressionable
                expressionable.AndIF(dto.search != "$", (plans, client) => plans.FName.Contains(dto.search));//添加条件
                Expression<Func<tCanteenPlan, tCanteenClient, bool>> expression = expressionable.ToExpression();//将Expressionable转为Expression

                int totalCount = 0;
                int totalPage = 0;
                var lst = await Task.Run(() => _db.Queryable<tCanteenPlan, tCanteenClient>((plans, client) => new JoinQueryInfos(
                    JoinType.Left, client.FPlanID.Equals(plans.Id)
                    )).Where(expression).OrderBy((plans, client) => plans.CreateTime, OrderByType.Desc).Select((plans, client) => new GetPlanOutput
                    {
                        ClientName = client.FName,
                        ClientID = client.Id,
                        Id= plans.Id,
                        Name= plans.FName,
                        ChageDate=plans.FChageDate,
                        ShowType=plans.FShowType
                    }).ToPageList(dto.PageNum, dto.PageSize, ref totalCount, ref totalPage));
                return result.Success(lst, totalPage);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--GetPlan:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取方案详情
        /// </summary>
        /// <param name="planID"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<CanteenPlanOutput>> GetPlanByID(string planID)
        {
            ResultMsg<CanteenPlanOutput> result = new ResultMsg<CanteenPlanOutput>();
            try
            {
                var entity = await _CanteenPlan.GetByIdAsync(planID);
                CanteenPlanOutput dao=_mapper.Map<CanteenPlanOutput>(entity);
                if (dao != null)
                {
                    var files = (await _File.GetListAsync(t => t.FPlanID.Equals(planID))).OrderBy(t=>t.FSort).ToList();
                    dao.Filelst=_mapper.Map<List<FileOutput>>(files);
                }
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--GetPlanByID:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取方案详情按展示方式
        /// </summary>
        /// <param name="planID"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<CanteenPlanOutput>> GetPlanByID2(int planID)
        {
            ResultMsg<CanteenPlanOutput> result = new ResultMsg<CanteenPlanOutput>();
            try
            {
                var entity = await _CanteenPlan.GetByIdAsync(planID);
                CanteenPlanOutput dao = _mapper.Map<CanteenPlanOutput>(entity);
                if (dao != null)
                {
                    var files = (await _File.GetListAsync(t => t.FPlanID.Equals(planID) && t.FShowType.Equals(entity.FShowType))).OrderBy(t => t.FSort).ToList();
                }
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--GetPlanByID2:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 互换排序
        /// </summary>
        /// <param name="fileOne"></param>
        /// <param name="fileTwo"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> ChangeSort(string fileOne, string fileTwo)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var one = await _File.GetByIdAsync(fileOne);

                var two = await _File.GetByIdAsync(fileTwo);

                int sortOne = one.FSort;
                int sortTwo = two.FSort;

                one.FSort = sortTwo;
                two.FSort = sortOne;

                await _File.UpdateAsync(one);
                await _File.UpdateAsync(two);

                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--ChangeSort:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> DelFile([FromBody] object[] fileIDs)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                bool b = await _File.DeleteByIdsAsync(fileIDs);
                if (b)
                    return result.Success();
                return result.Error();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--DelFile:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 删除方案
        /// </summary>
        /// <param name="planIDs"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> DelPlan([FromBody] object[] planIDs)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _CanteenClient.DeleteByIdAsync(planIDs);

                List<tCanteenClient> list = await _CanteenClient.GetListAsync(t => t.FPlanID.Equals(planIDs));

                if (list != null)
                {

                    foreach (var item in list)
                    {
                        item.FPlanID = "";
                        await _CanteenClient.UpdateAsync(item);
                    }
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--DelPlan:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取去所有已上传的背景音乐
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<List<string>>> GetAllBGM()
        {
            ResultMsg<List<string>> result = new ResultMsg<List<string>>();
            try
            {
                DirectoryInfo dir_Img = new DirectoryInfo(FileOperate.GetPath("file/Canteen/BGM"));
                List<string> lst = new List<string>();
                foreach (FileInfo item in dir_Img.GetFiles())
                {
                    lst.Add(item.Name);
                }
                return result.Success(lst);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("CanteenPlanController--GetAllBGM:" + ex.ToString());
                return result.Exception();
            }
        }
    }
}
